package demo.io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 读取速度测试
 *
 * @author liuteng
 * @date 2017/8/23 09:56
 */
public class MapIO {

    public static void main(String[] args) {
        mapRead();
        System.out.println("=======================");
        normal();
    }

    public static void normal() {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;

        try {
            randomAccessFile = new RandomAccessFile("d:/eclipse-neon.rar", "rw");
            fileChannel = randomAccessFile.getChannel();
            long startTime = System.currentTimeMillis();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) randomAccessFile.length());
            byteBuffer.clear();
            fileChannel.read(byteBuffer);
            long endTime = System.currentTimeMillis();
            System.out.println("Read time:" + (endTime - startTime) + "ms");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void mapRead() {
        RandomAccessFile randomAccessFile = null;
        FileChannel fileChannel = null;
        try {
            randomAccessFile = new RandomAccessFile("d:/eclipse-neon.rar", "rw");
            fileChannel = randomAccessFile.getChannel();
            long startTime = System.currentTimeMillis();
            fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
            long endTime = System.currentTimeMillis();
            System.out.println("Read time:" + (endTime - startTime) + "ms");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
